from rest_framework import serializers
from django.contrib.auth import get_user_model
from rest_framework.validators import UniqueValidator
from .models import Grained

User = get_user_model()

class UserDetailSerializer(serializers.ModelSerializer):
    '''
    用户详情序列化
    '''


    class Meta:
        model = User
        fields = ("id","username","name","gender","birthday","email","mobile","department","role","auth_group","avator")



class UserRegistrySerializer(serializers.ModelSerializer):
    '''
    用户注册
    '''
    username = serializers.CharField(required=True, allow_blank=False,help_text="用户名",label="用户名",
                                     validators=[UniqueValidator(queryset=User.objects.all(), message="用户已存在")])
    password = serializers.CharField(style={'input_type': 'password'}, help_text="密码", label="密码", write_only=True)
    # auth_group = serializers.ListField(label="所属权限组",help_text="所属权限组")


    class Meta:
        model = User
        fields = ("username", "name", "password","department","role","auth_group","mobile")



class AccountUpdateSerializer(serializers.ModelSerializer):
    '''
    修改用户密码
    '''


    class Meta:
        model = User
        fields = ('password',)

    def update(self, instance, validated_data):
        for attr, value in validated_data.items():
            if attr == 'password':
                instance.set_password(value)
            else:
                setattr(instance, attr, value)
        instance.save()
        return instance


class UserAuthGroupDetailSerializer(serializers.ModelSerializer):
    '''序列化权限组'''

    create_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S")
    update_time = serializers.DateTimeField(format="%Y-%m-%d %H:%M:%S")
    permissions = serializers.JSONField(label="权限组权限", help_text="权限组权限")

    class Meta:
        model = Grained
        fields = "__all__"



class UserAuthGroupCreateSerializer(serializers.ModelSerializer):
    '''创建'''

    permissions = serializers.JSONField(label="权限组权限",help_text="权限组权限")


    class Meta:
        model = Grained
        fields = ("auth_group","permissions")